package org.pps.gl.client;

import java.util.Date;
import org.pps.gl.client.events.ConnectedEvent;
import org.pps.gl.client.events.ConnectedEventHandler;
import org.pps.gl.client.events.RefreshUserEvent;
import org.pps.gl.client.events.RefreshUserEventHandler;
import org.pps.gl.client.events.SignOutEvent;
import org.pps.gl.client.events.SignOutEventHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ConnectionManager implements HasHandlers {
	private HandlerManager handlerManager;

	public ConnectionManager() {
		handlerManager = new HandlerManager(this);
	}

	public void connect() {
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		String cookie = Cookies.getCookie("pps-sid");
		System.out.println("Cookie = " + cookie);
		if (cookie != null)
			loginService.login(cookie, new AsyncCallback<LoginInfo>() {
				public void onFailure(Throwable error) {
					// Window.alert("No :(");
				}

				public void onSuccess(LoginInfo result) {
					// Window.alert("Result " + result.getEmailAddress());
					if (result.isLoggedIn()) {
						LoginInfo.setCurrentUser(result);
						final long DURATION = 1000 * 60 * 60 * 24 * 14; // duration
						Date expires = new Date(System.currentTimeMillis()
								+ DURATION);
						Cookies.setCookie("pps-sid", result.getSessionId(),
								expires);
						Pps_gl.getCm().fireEvent(new ConnectedEvent(result));

						History.fireCurrentHistoryState();
					}
				}
			});
	}

	public void connect(String email, String pwd) {
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(email, pwd, new AsyncCallback<LoginInfo>() {
			public void onFailure(Throwable error) {
				Window.alert("No :(");
			}

			public void onSuccess(LoginInfo result) {
				if (result.isLoggedIn()) {
					// Window.alert("Result " + result.getSessionId()+ " " +
					// result.getEmailAddress()+ " " + result.getFirstname() +
					// " " + result.getLastname());
					final long DURATION = 1000 * 60 * 60 * 24 * 14; // duration
					Date expires = new Date(System.currentTimeMillis()
							+ DURATION);
					System.out.println("Session id " + result.getSessionId());
					Cookies.setCookie("pps-sid", result.getSessionId(), expires);
					LoginInfo.setCurrentUser(result);
					Pps_gl.getCm().fireEvent(new ConnectedEvent(result));
				} else {
					Window.alert("Utilisateur non existant ou mauvaise combinaison login/mot de passe.");
				}

			}
		});
	}

	public void logout() {
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.logout(Cookies.getCookie("pps-sid"),
				new AsyncCallback<Boolean>() {
					public void onFailure(Throwable error) {
						Window.alert("Erreur de connexion avec le serveur");
					}

					public void onSuccess(Boolean result) {
						Cookies.removeCookie("pps-sid");
						Pps_gl.getCm().fireEvent(new SignOutEvent());
					}
				});
	}

	public void refresh() {
		@SuppressWarnings("unused")
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		GetInfoServiceAsync getInfoService = GWT.create(GetInfoService.class);
		getInfoService.getUserLoginInfo(LoginInfo.getCurrentUser(),
				new AsyncCallback<LoginInfo>() {

					@Override
					public void onFailure(Throwable caught) {
						
					}

					@Override
					public void onSuccess(LoginInfo result) {
						LoginInfo.setCurrentUser(result);
						Pps_gl.getCm().fireEvent(new RefreshUserEvent(result));
					}
				});

	}

	@Override
	public void fireEvent(GwtEvent<?> event) {
		handlerManager.fireEvent(event);
	}

	public HandlerRegistration addConnectedEventHandler(
			ConnectedEventHandler handler) {
		return handlerManager.addHandler(ConnectedEvent.TYPE, handler);
	}

	public HandlerRegistration addSignOutHandler(SignOutEventHandler handler) {
		return handlerManager.addHandler(SignOutEvent.TYPE, handler);
	}

	public HandlerRegistration addRefreshUserHandler(
			RefreshUserEventHandler handler) {
		return handlerManager.addHandler(RefreshUserEvent.TYPE, handler);
	}

}
